import esriLoader from 'esri-loader'
import Vue from 'vue'
//import Global from './components/Global'
import Bus from './Bus.js'
function getchangeLayer(a, b) {
  var index;
  for (var i = 0; i < a.length; i++) {
    for (var k = 0; k < b.length; k++) {
      if (a[i].LayerName == b[k].LayerName) {
        break;
      }
    }
    if (k >= b.length) {
      return i;
    }
  }
  return
}
var addLayer = (layer, status,mapId) => {
  esriLoader.loadModules(["esri/map", "esri/layers/ArcGISDynamicMapServiceLayer", "esri/layers/ArcGISTiledMapServiceLayer","widget/MapManager"])
    .then(([Map, ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer,MapManager]) => {
      // you can now create a new FlareClusterLayer and add it to a new map
      // alert(123);
      var map = MapManager.getMap(mapId);
      map.infoWindow.hide();
      if (status) {
        switch (layer.type) {
          case "Folder":
            break;
          case "Vector":
            var layerInfo = layer.ILayer;
            console.log(Vue.prototype.GLOBAL);
            var la = Vue.prototype.GLOBAL.layerBox;
            var arr = [1, 2];
            var ar = arr.contains(2);
            //if (!Vue.prototype.GLOBAL.layerBox.contains(layerInfo)) {

              if (layerInfo.DisplayModel) {
                var layer2 = new ArcGISTiledMapServiceLayer(layerInfo.DisplayUrl, {
                  // id: layerInfo.LayerName,
                  id: layer.label,
                  opacity:(layerInfo.Transparent||80)/100.0

                });
                map.addLayer(layer2);
              } else {
                var url = layerInfo.DisplayUrl;
                // var url="http://localhost:6080/arcgis/rest/services/test_feature/MapServer";
                var layer2 = new ArcGISDynamicMapServiceLayer(url, {
                  // id: layerInfo.LayerName,
                  id: layer.label,
                  opacity:(layerInfo.Transparent||80)/100.0
                });
                layer2.setVisibleLayers([layerInfo.QueryIndexArray]);
                map.addLayer(layer2);
              }


            if(layer.IsQuery){
              Bus.$emit("addLayerBox",layer);
            }
            break;
          case "Tile":
            var tileInfo = layer.ILayer;

              var layer2 = new ArcGISTiledMapServiceLayer(tileInfo.Config, {
                // id: tileInfo.Name,
                id: layer.label,
                opacity:(tileInfo.Transparent||80)/100.0
              });
              map.addLayer(layer2);
              Bus.$emit("addLayerBox",layer);
            break;
        }
      } else {
        if (map.getLayer(layer.label)) {
          map.removeLayer(map.getLayer(layer.label));
          Bus.$emit("removeLayerBox",layer);
        }
      }

    })
    .catch(err => {
      // handle any errors
      //alert(456)
      console.error(err);
    });



}
var addHisLayer = (layer, status,mapId) => {
  esriLoader.loadModules(["esri/map", "esri/layers/ArcGISDynamicMapServiceLayer", "esri/layers/ArcGISTiledMapServiceLayer","widget/MapManager"])
    .then(([Map, ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer,MapManager]) => {
      var map = MapManager.getMap(mapId);
      if (status) {
        switch (layer.type) {
          case "Folder":
            break;
          case "Vector":
            var layerInfo = layer.ILayer;
            console.log(Vue.prototype.GLOBAL);
            var la = Vue.prototype.GLOBAL.layerBox;
            var arr = [1, 2];
            var ar = arr.contains(2);
            //if (!Vue.prototype.GLOBAL.layerBox.contains(layerInfo)) {


              if (layerInfo.DisplayModel) {
                var layer2 = new ArcGISTiledMapServiceLayer(layerInfo.DisplayUrl, {
                  // id: layerInfo.LayerName,
                  id: layer.label,

                });
                map.addLayer(layer2);
              } else {
                var url = layerInfo.DisplayUrl;
                // var url="http://localhost:6080/arcgis/rest/services/test_feature/MapServer";
                var layer2 = new ArcGISDynamicMapServiceLayer(url, {
                  // id: layerInfo.LayerName,
                  id: layer.label,
                });
                layer2.setVisibleLayers([layerInfo.QueryIndexArray]);
                map.addLayer(layer2);
              }


            //  } else {
            //   layerBox.remove(layerInfo);
            //  }
            break;
          case "Tile":
            var tileInfo = layer.ILayer;
            //if (layer.ILayer.Tile.length) {
              var layer2 = new ArcGISTiledMapServiceLayer(tileInfo.Config, {
                // id: tileInfo.Name,
                id: layer.label
              });
              map.addLayer(layer2);
           // }
            break;
        }
      } else {
        if (map.getLayer(layer.label)) {
          map.removeLayer(map.getLayer(layer.label));
        }
      }

    })
    .catch(err => {
      // handle any errors
      //alert(456)
      console.error(err);
    });

},
  addPositionLayer = function (mapId,layerData) {
    esriLoader.loadModules(["widget/MapManager","esri/symbols/TextSymbol","esri/symbols/Font","esri/symbols/PictureMarkerSymbol","esri/layers/GraphicsLayer","esri/graphic"])
      .then(([MapManager,TextSymbol,Font,PictureMarkerSymbol,GraphicsLayer,Graphic]) => {
        var map = MapManager.getMap(mapId);
        var layer = map.getLayer("posintionLayer");
        if(layer){
          layer.clear();
        }else{
          layer = new GraphicsLayer({id:"posintionLayer"});
          map.addLayer(layer);
        }
        var textcolor =  "#000";
        var fontsize =  "16px";
        var fontfamily = "Microsoft Yahei";
        var font = new Font();
        font.setSize(fontsize).setWeight(esri.symbol.Font.WEIGHT_BOLD).setFamily(fontfamily);
       
        
     
          

        var symbol = new PictureMarkerSymbol({url:"./static/image/position/point.png","height":20,
          "width":20});
        //var symbol = new PictureMarkerSymbol('/images/diamond.png', 25, 25);
        for(var i = 0;i<layerData.length;i++){
          if(layerData){
            var pt = new esri.geometry.Point(layerData[i].Lon,layerData[i].Lat,map.spatialReference)
            var graphic =  new Graphic({
              geometry:pt,//{x:,y:layerData[i].Lat,map.spatialReference},
              attributes:layerData[i]
            })
            var indexLabel = new TextSymbol(layerData[i].index.toString()).setFont(font).setColor(new esri.Color(textcolor)).setOffset(0,10);
            var graphText = new Graphic(pt, indexLabel,{Name:"text"});
            graphic.setSymbol(symbol);
            layer.add(graphic);
            layer.add(graphText);
          }
        }
      })
.catch(err => {
  // handle any errors
  //alert(456)
  console.error(err);
});
  },
  positionAndHeight = function (heightGraphic,currentGraphic,map) {
    esriLoader.loadModules(["esri/symbols/PictureMarkerSymbol"])
      .then(([PictureMarkerSymbol]) => {
        var layer = map.getLayer("posintionLayer"),graphics = layer.graphics;
        var symbol = new PictureMarkerSymbol({url:"./static/image/position/point.png","height":20,
          "width":20});
        var heightSsymbol = new PictureMarkerSymbol({url:"./static/image/position/pointHight.png","height":20,
          "width":20});
        for(var i = 0;i<graphics.length;i++){
          if(heightGraphic && heightGraphic.Name == graphics[i].attributes.Name){
            graphics[i].setSymbol(symbol);
          }
          if(currentGraphic && currentGraphic.Name == graphics[i].attributes.Name){
            graphics[i].setSymbol(heightSsymbol);
            console.log(graphics[i].geometry);
            if(map.getZoom()>7){
              map.centerAt(graphics[i].geometry);
            }else{
              map.centerAndZoom(graphics[i].geometry,8)
            }          
          }
        }

      })
      .catch(err => {
        // handle any errors
        //alert(456)
        console.error(err);
      });
  },
  mapPosition = function(mapId,lon,lat){
    var self = this;
    esriLoader.loadModules(["widget/MapManager","esri/geometry/Point","esri/graphic","esri/symbols/PictureMarkerSymbol"])
      .then(([MapManager,Point,Graphic,PictureMarkerSymbol]) => {
       var map = MapManager.getMap(mapId),extent = map.extent;
       if(!(lon>118 && lon<120.5)){
         this.$Message.warning('经度不在地图范围内！！');
         return
       }else if(!(lat>29 && lat<30.5)){
         this.$Message.warning('纬度不在地图范围内！！');
         return;
       }

        var point;
       // if(map.spatialReference=="4490"){
         // point = new Point(lon, lat, new esri.SpatialReference({ wkid: 4490 }));
         point = new Point(lon, lat, map.spatialReference);
         
       // }else{
        //  point = new Point(lon, lat);
      //  }
         
        var symbol = new PictureMarkerSymbol({url:"./static/image/position/mapPosition.png","height":20,
          "width":20});
        var graphic =  new Graphic({
          geometry:point
        })
        graphic.setSymbol(symbol);
        map.graphics.add(graphic);
        if(map.getZoom()>7){
          map.centerAt(point);
        }else{
          map.centerAndZoom(point,8)
        } 
      // map.centerAt(point);
      })
      .catch(err => {
        // handle any errors
        //alert(456)
        console.error(err);
      });
  },
  clearGraphic=function(mapId){
    esriLoader.loadModules(["widget/MapManager"])
    .then(([MapManager]) => {
      var map = MapManager.getMap(mapId);
      var layer = map.getLayer("posintionLayer");
      if(layer){
        layer.clear();
      }
      map.graphics.clear();
    })
  }
export default {
  addLayer,
  addHisLayer,
  addPositionLayer,
  positionAndHeight,
  mapPosition,
  clearGraphic
}
